/*
+--------------------------
| FreeloaderOS v0.0.1
|  - Microkernel
+--------------------------
| Written by Alec Hussey
| Copyright (c) 2007
|  - Deus X Foundation
+---------------------------
*/

/*
 * Standard C Library
 */

#include <math.h>
#include <stdio.h>
#include <stdarg.h>
#include <stdbool.h>
#include <screen.h>
#include <system.h>
#include <keyboard.h>

/*
Checks for the appropriate datatype
of any given input data and looks for
the appropriate function in order to
print the data to the screen.
*/
void printf(unsigned char *str, ...)
{
	char character = *str;
	char *str2;
	int intv;
	va_list args;
	va_start(args, str);
	
	while (character != '\0')
	{
		if (character == '\0')
		{
			str++;
			character = *str;
			
			switch (character)
			{
			case 'c':
				character = (unsigned char) va_arg(args, unsigned long);
				putch(character);
				break;
			case 's':
				str2 = va_arg(args, char*);
				putstr(str2);
				break;
			case 'd':
				intv = va_arg(args, int);
				putint(intv);
				break;
			case 'x':
				convertDecimaltoHexa(va_arg(args, unsigned long));
				break;
			default:
				putch('%');
				break;
			}
		}
		else
		{
			putch(character);
		}
		str++;
		character = *str;
		*str = '\0';
	}
}

/*
Take and print a given integer
to the screen.
*/
void printint(unsigned long int num)
{
	unsigned int i = 0;
	unsigned char ch[20] = {" "};
	
	while (num > 0)
	{
		*(ch + i) = (num % 10) + 48;
		num /= 10;
		i++;
	}
	
	for (; i > 0; i--)
		putch((unsigned char)ch[i]);
}

/*
Checks keyboard input and chooses the
appropriate action to take.
*/
void scanf(unsigned char *opvar, unsigned int x, unsigned int y)
{
	int i;
	int maxi = 0;
	int current_posx = get_current_pos('x');
	unsigned char character;
	
	while ((character = get_char()) != 10 )
	{
		switch (character)
		{
		case KEY_F12:
			// Shutdown system
			break;
		case KEY_LEFT:
			if (current_posx >= 0)
			{
				current_posx--;
				set_current_pos('x', current_posx);
				move_csr();
			}
			break;
		case KEY_RIGHT:
			if (current_posx <= 80)
			{
				current_posx++;
				set_current_pos('x', current_posx);
				move_csr();
			}
			break;
		case '\b':
			if (current_posx <= 80)
			{
				putch(' ');
				*(opvar + current_posx) = ' ';
				current_posx--;
				set_current_pos('x', current_posx);
				move_csr();
			}
			break;
		default:
			putch(character);
			*(opvar + current_posx) = character;
			current_posx++;
			set_current_pos('x', current_posx);
		}
	}
	*(opvar + current_posx) = '\0';
}
